package it.dornauf.java.web2printer;

/**
$Id: $ 
Copyright [2001, 2013] [Oliver Dornauf, pda-systems.COM]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Vector;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>Implementation of <strong>Web2Printer</strong> as a servlet filter with minimal
 * footprint.</p>  
 *
 *
 * @author <a href="mailto:info@pda-systems.com>Oliver Dornauf</a>
 */

public class Web2PrinterFilter implements Filter
{
    private FilterConfig filterConfig;
    private Web2Printer web2printer;
    private boolean localePerRequest = false;
    private Locale defaultLocale;

    public void init(FilterConfig filterConfig) throws ServletException {

        this.filterConfig = filterConfig;

        String startToken = filterConfig.getInitParameter("startToken");
        String endToken = filterConfig.getInitParameter("endToken");
        if (startToken != null && endToken != null) {
            web2printer = new Web2Printer(startToken, endToken);
        } else {
            web2printer = new Web2Printer();
        }
        
        String defaultLocaleName = filterConfig.getInitParameter("defaultLocale");
        if (defaultLocaleName == null) {
            defaultLocale = Locale.ENGLISH;
        } else {
            defaultLocale = new Locale(defaultLocaleName);
        }
        localePerRequest = new Boolean(filterConfig.getInitParameter("localePerRequest")).booleanValue();
        
    }

    public void destroy() {
        this.filterConfig = null;
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {

        if (filterConfig == null)
            return;

        if (request.getParameter("web2printer") != null && request instanceof HttpServletRequest) {
            PrintWriter out = response.getWriter();
            Web2PrinterResponseWrapper wrapper = new Web2PrinterResponseWrapper((HttpServletResponse) response);
            chain.doFilter(request, wrapper);

            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            StringBuffer content = wrapper.getContent();
            long startTimeMillis = System.currentTimeMillis();

            Vector<String> hyperlinks = new Vector<String>();
            Vector<String> images = new Vector<String>();

            Web2Printer.ImageProcessing img = web2printer.parseImageParameter(httpServletRequest.getParameter("img"));
            Web2Printer.LinkProcessing lnk = web2printer.parseLinkProcessingParameter(httpServletRequest
                    .getParameter("lnk"));
            // Web2Printer.TagProcessing tgs = web2printer.parseTagProcessingParameter(request.getParameter("tgs"));

            StringBuffer htmlBody = web2printer.getHtmlBody(content);
            StringBuffer htmlHeader = web2printer.getHtmlHeader(content);
            StringBuffer htmlFooter = web2printer.getHtmlFooter(content);

            Locale currentLocale = null;
            if (localePerRequest) {
                currentLocale = httpServletRequest.getLocale();
            } else {
                currentLocale = defaultLocale;
            }
            ResourceBundle bundle = null;
            try {
                bundle = ResourceBundle.getBundle("it.dornauf.java.web2printer.messages", currentLocale);
            } catch (MissingResourceException ex) {
                bundle = ResourceBundle.getBundle("it.dornauf.java.web2printer.messages");
            }
            
            URL requestURL = new URL(httpServletRequest.getRequestURL().toString());
            if (lnk != Web2Printer.LinkProcessing.NOTHING && lnk != Web2Printer.LinkProcessing.FRAUD) {
                String protocol = httpServletRequest.getProtocol();
                String host = requestURL.getHost();
                int port = requestURL.getPort();
                htmlBody = web2printer.processLinks(htmlBody, lnk, protocol, host, port, hyperlinks);
            }
            if (img != Web2Printer.ImageProcessing.NOTHING && img != Web2Printer.ImageProcessing.FRAUD) {
                htmlBody = web2printer.processImages(htmlBody, img, images,bundle);
            }
            Long runtimeTimeMillis = new Long(System.currentTimeMillis() - startTimeMillis);
            String[] authorAndCopyright = web2printer.getAuthor(htmlHeader);
            htmlBody.append(web2printer.createFooter(runtimeTimeMillis,  requestURL.toString(), hyperlinks, images,authorAndCopyright[0], authorAndCopyright[1], bundle));
            
            int length = htmlHeader.toString().length() + htmlBody.toString().length() + htmlFooter.toString().length();
            response.setContentLength(length);
            out.write(htmlHeader.toString());
            out.write(htmlBody.toString());
            out.write(htmlFooter.toString());
            out.close();

        } else {
            chain.doFilter(request, response);
        }
    }
}
